<template>
  <div class="erp-price">
    <el-card shadow="never">
      <template #header>
        <div class="erp-price__header">
          <span>价目表</span>
          <div>
            <el-button type="primary" size="small" @click="openEdit()">新建</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" class="erp-price__search" @submit.prevent>
        <el-form-item label="类型">
          <el-select v-model="query.billType" clearable placeholder="全部">
            <el-option value="PO_IN" label="采购入库" />
            <el-option value="SO_OUT" label="销售出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="往来方">
          <el-select v-model="query.partyId" filterable remote reserve-keyword :remote-method="remoteParty" :loading="loadingParty" clearable placeholder="输入编码/名称">
            <el-option v-for="p in partyOptions" :key="p.id" :label="p.label" :value="String(p.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料">
          <el-select v-model="query.materialId" filterable remote reserve-keyword :remote-method="remoteMaterial" :loading="loadingMaterial" clearable placeholder="输入编码/名称">
            <el-option v-for="m in materialOptions" :key="m.materialId" :label="`${m.materialCode} | ${m.materialName}`" :value="String(m.materialId)" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small">
        <el-table-column prop="billType" label="类型" width="100" />
        <el-table-column prop="partyId" label="往来方ID" width="120" />
        <el-table-column prop="materialId" label="物料ID" width="120" />
        <el-table-column prop="uomId" label="单位ID" width="120" />
        <el-table-column label="价格" width="180">
          <template #default="{ row }">
            {{ row.price }}
            <el-tag size="small" :type="row.taxIncluded===1?'success':'info'" style="margin-left:6px;">{{ row.taxIncluded===1 ? '含税' : '未税' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率%" width="120" />
        <el-table-column prop="startTime" label="生效开始" width="180" />
        <el-table-column label="生效结束" width="180">
          <template #default="{ row }">{{ row.endTime || '长期' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button link size="small" type="primary" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="erp-price__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="520px">
      <el-form ref="formRef" :model="form" label-width="96px">
        <el-form-item label="类型">
          <el-select v-model="form.billType" placeholder="请选择">
            <el-option value="PO_IN" label="采购入库" />
            <el-option value="SO_OUT" label="销售出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="往来方">
          <el-select v-model="form.partyId" filterable remote reserve-keyword :remote-method="remoteParty" :loading="loadingParty" clearable placeholder="输入编码/名称">
            <el-option v-for="p in partyOptions" :key="p.id" :label="p.label" :value="String(p.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料">
          <el-select v-model="form.materialId" filterable remote reserve-keyword :remote-method="remoteMaterial" :loading="loadingMaterial" placeholder="输入编码/名称">
            <el-option v-for="m in materialOptions" :key="m.materialId" :label="`${m.materialCode} | ${m.materialName}`" :value="String(m.materialId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="form.uomId" clearable filterable :disabled="!form.materialId" placeholder="可空：基准单位">
            <el-option v-for="u in uomOptions" :key="u.uomId" :label="`${u.uomCode} | ${u.uomName}${u.base?'(基本)':''}${u.rate && !u.base ? ' ×'+u.rate : ''}`" :value="String(u.uomId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="form.price" :min="0" :precision="6" />
        </el-form-item>
        <el-form-item label="价格类型">
          <el-radio-group v-model="form.taxIncluded">
            <el-radio :label="1">含税</el-radio>
            <el-radio :label="0">未税</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="税率%">
          <el-input-number v-model="form.taxRate" :min="0" :precision="6" />
        </el-form-item>
        <el-form-item label="生效开始">
          <el-date-picker v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="生效结束">
          <el-date-picker v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex:1;text-align:center;">
          <el-button @click="drawerVisible=false">取消</el-button>
          <el-button type="primary" @click="onSave">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { pagePrice, createPrice, updatePrice, deletePrice } from '@/api/erp/price'
import { pageSupplier, pageCustomer } from '@/api/erp/party'
import { pageMaterial } from '@/api/erp/material'
import { ElMessage } from 'element-plus'
import { listUomConv } from '@/api/erp/uom'

const list = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{ billType?: string; materialId?: string; partyId?: string }>({ billType: '', materialId: '', partyId: '' })
const materialOptions = ref<any[]>([])
const partyOptions = ref<any[]>([])
const loadingMaterial = ref(false)
const loadingParty = ref(false)

const drawerVisible = ref(false)
const drawerTitle = ref('新建价格')
const form = reactive<any>({ priceId: '', billType: 'PO_IN', partyId: '', materialId: '', uomId: '', price: 0, taxIncluded: 1, taxRate: 0, startTime: '', endTime: '' })
const uomOptions = ref<any[]>([])

const load = async () => {
  const res = await pagePrice({ pageNum: pageNum.value, pageSize: pageSize.value, billType: query.billType || undefined, materialId: query.materialId || undefined, partyId: query.partyId || undefined })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onSearch = () => { pageNum.value = 1; load() }
const onReset = () => { query.billType=''; query.materialId=''; query.partyId=''; onSearch() }
const onSizeChange = (s:number) => { pageSize.value = s; pageNum.value = 1; load() }
const onPageChange = (p:number) => { pageNum.value = p; load() }

const openEdit = (row?: any) => {
  if (row) { Object.assign(form, row); drawerTitle.value = '编辑价格' } else { Object.assign(form, { priceId: '', billType: 'PO_IN', partyId: '', materialId: '', uomId: '', price: 0, taxIncluded: 1, taxRate: 0, startTime: '', endTime: '' }); drawerTitle.value = '新建价格' }
  drawerVisible.value = true
}

const onSave = async () => {
  if (form.priceId) await updatePrice(String(form.priceId), form)
  else await createPrice(form)
  ElMessage.success('保存成功')
  drawerVisible.value = false
  load()
}

const onDelete = async (row:any) => { await deletePrice(String(row.priceId)); ElMessage.success('已删除'); load() }

const remoteMaterial = async (queryStr:string) => { loadingMaterial.value = true; try { const res = await pageMaterial({ pageNum:1, pageSize:20, materialCode: queryStr, materialName: queryStr }); materialOptions.value = res?.data?.records || [] } finally { loadingMaterial.value=false } }
const remoteParty = async (queryStr:string) => {
  loadingParty.value = true
  try {
    if (form.billType === 'PO_IN') {
      const res = await pageSupplier({ pageNum:1, pageSize:20, code:queryStr, name:queryStr })
      partyOptions.value = (res?.data?.records||[]).map((s:any)=>({ id: s.supplierId, label: `${s.supplierCode} | ${s.supplierName}` }))
    } else {
      const res = await pageCustomer({ pageNum:1, pageSize:20, code:queryStr, name:queryStr })
      partyOptions.value = (res?.data?.records||[]).map((c:any)=>({ id: c.customerId, label: `${c.customerCode} | ${c.customerName}` }))
    }
  } finally { loadingParty.value = false }
}

onMounted(load)

watch(() => form.materialId, async (val) => {
  uomOptions.value = []
  form.uomId = ''
  if (!val) return
  const res = await listUomConv(String(val))
  uomOptions.value = res?.data || []
})
</script>

<style scoped lang="scss">
.erp-price {
  &__header { display: flex; align-items: center; justify-content: space-between; }
  &__pagination { margin-top: 12px; display: flex; justify-content: flex-end; }
}
</style>


